package com.zbw.printlibrary.printSub;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import com.rt.printerlibrary.bean.UsbConfigBean;
import com.rt.printerlibrary.connect.PosInterface;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.PrintThreadPoolManager;
import com.zbw.printlibrary.util.rongda.ESCCmdManager;
import com.zbw.printlibrary.util.rongda.PosManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.MODE_PRIVATE;

/**
 * 作者 ：Wesley
 * 时间 ：2024-02-20 11:32
 * 这个类是干嘛的？：PrintRongDa
 */
public class PrintRongDa extends PrinterControlCommon {
   private PosManager posManager;
   private Context mContext;
   private IPrintCallBack mCallBack;
   private int USB_PID = 0;
   private int USB_VID = 0;

   public PrintRongDa(Context context, IPrintCallBack callBack, int USB_VID,int USB_PID) {
      mContext = context;
      mCallBack = callBack;
      this.USB_PID = USB_PID;
      this.USB_VID = USB_VID;
      posManager = new PosManager(mContext) {
         @Override
         public void posStatusCallback(PosInterface posInterface, int status) {

         }

         @Override
         public void posMsgCallback(PosInterface posInterface, byte[] bytes) {

         }
      };
   }

   public PrintRongDa(Context context, IPrintCallBack callBack) {
      mContext = context;
      mCallBack = callBack;
      posManager = new PosManager(mContext) {
         @Override
         public void posStatusCallback(PosInterface posInterface, int status) {

         }

         @Override
         public void posMsgCallback(PosInterface posInterface, byte[] bytes) {

         }
      };

   }

   public void getUSBPram() {
      SharedPreferences share = mContext.getSharedPreferences("SHEZHI", MODE_PRIVATE);
      USB_PID = share.getInt("USB_PID", 0);
      USB_VID = share.getInt("USB_VID", 0);
   }

   @Override
   public void connectPrinter() {
      if(USB_PID == 0 && USB_VID == 0){
         getUSBPram();
      }
      if(USB_PID == 0 && USB_VID == 0){
         mCallBack.onConnect("请先选择需要连接的打印机",false);
         return;
      }
      List<UsbDevice> printerDevices = getUsbPrinters();
      if(printerDevices.size() == 0){
         mCallBack.onConnect("没有发现可用打印机",false);
         return;
      }
      UsbDevice device = null;

      for (int i = 0; i < printerDevices.size(); i++) {
         if(printerDevices.get(i).getVendorId() == USB_VID && printerDevices.get(i).getProductId() == USB_PID){
            device = printerDevices.get(i);
            break;
         }
      }
      if(device == null){
         mCallBack.onConnect("没有匹配到对应的打印机",false);
         return;
      }
      mCallBack.onConnect("连接成功",true);
      connectUsbDevice(device);
   }

   /**
    * 连接打印机
    * connect printer
    * @param usbDevice
    */
   private void connectUsbDevice(UsbDevice usbDevice) {
      PendingIntent mPermissionIntent = PendingIntent.getBroadcast(mContext, 0,
              new Intent(mContext.getApplicationInfo().packageName), 0);
      UsbConfigBean usbconfigObj = new UsbConfigBean(mContext, usbDevice, mPermissionIntent);
      posManager.connectPrinter(usbconfigObj);
   }

   public List<UsbDevice> getUsbPrinters() {
      List<UsbDevice> usbDevices = new ArrayList<>();
      UsbManager mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
      HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
      Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

      while (deviceIterator.hasNext()) {
         UsbDevice device = deviceIterator.next();
         if (isPrinterDevice(device))
            usbDevices.add(device);
      }
      return usbDevices;
   }

   /**
    * 判断UsbDevice 是否为打印机类型设备
    * check a UsbDevice
    * @param device
    * @return true:打印机 false:非打印机
    */
   public static boolean isPrinterDevice(UsbDevice device) {
      if (device == null) {
         return false;
      }
      if (device.getInterfaceCount() == 0) {
         return false;
      }
      for (int i = 0; i < device.getInterfaceCount(); i++) {
         android.hardware.usb.UsbInterface usbInterface = device.getInterface(i);
         if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_PRINTER) {
            return true;
         }
      }
      return false;
   }

   @Override
   public void disConnectPrinter() {
      if(posManager != null){
         posManager.disconnectPrinter();
      }

   }

   @Override
   public void printTest(final List<String> strList) {
      if(strList.size() == 0){
         return;
      }
      PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
         @Override
         public void run() {
            try {
               ESCCmdManager manager = new ESCCmdManager();
               manager.setTextAlignCenter().setTextChartSet("GBK").setTextFontDoubleWidthHeight(true,true).setTextBold(true).addText(strList.get(0)).addLineFeed();
               for (int i = 1; i < strList.size(); i++) {
                  manager.setTextAlignLeft().setTextChartSet("GBK").setTextFontDoubleWidthHeight(false,false).setTextBold(false).addText(strList.get(i)).addLineFeed();
               }
               posManager.sendEscMsgToPrinter(manager.useAllCutter().build());
               mCallBack.onPrintResult(true);
            } catch (Exception e) {
               e.printStackTrace();
               mCallBack.onPrintResult(false);
            }
         }
      });

   }

   @Override
   public void printString(final List<AttributeBean> testList) {
      PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
         @Override
         public void run() {
            try {
               ESCCmdManager manager = new ESCCmdManager();
               for (int i = 0; i < testList.size(); i++) {
                  AttributeBean item = testList.get(i);
                  if(item.getContext_type() == 1){
                     switch (item.getFont_gray()) {
                        case 0:
                           manager.setAlignLeft();//居左
                           break;
                        case 1:
                           manager.setAlignCenter();//居中
                           break;
                        case 2:
                           manager.setAlignRight();//居右
                           break;
                     }
                     manager.setBmpLimitWidth(40);//设置 图片宽度
                     manager.addBmp(item.getBitmap());//设置 图片宽度
                  }else {//打印文字
                     if(item.isBold()){
                        manager.setTextBold(true);
                     }else {
                        manager.setTextBold(false);
                     }
                     switch (item.getFont_gray()) {
                        case 0:
                           manager.setTextAlignLeft();//居左
                           break;
                        case 1:
                           manager.setTextAlignCenter();//居中
                           break;
                        case 2:
                           manager.setTextAlignRight();//居右
                           break;
                     }
                     if(item.getFont_size() == 0){
                        manager.setTextFontDoubleWidthHeight(false,false);//小字体
                     }else {
                        manager.setTextFontDoubleWidthHeight(true,true);//小字体
                     }
                     manager.setTextChartSet("GBK").addText(item.getContext());
                  }
                  manager.addLineFeed();
               }
               //切纸
               posManager.sendEscMsgToPrinter(manager.useAllCutter().build());
               mCallBack.onPrintResult(true);
               //closeBitmap(testList);
            } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
               mCallBack.onPrintResult(false);
            }
         }
      });



   }

   @Override
   public void printString(List<AttributeBean> testList, int width) {
      printString(testList);
   }

   @Override
   public void printStringAndBitmap(final List<String> testList, final LinkedHashMap<Integer, Bitmap> bitmapMap) {
      PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
         @Override
         public void run() {
            try {
               ESCCmdManager manager = new ESCCmdManager();
               String msg;
               for (int i = 0; i < testList.size(); i++) {
                  msg = testList.get(i);
                  if(i == 0 || i == 1){
                     manager.setTextAlignCenter().setTextChartSet("GBK").setTextFontDoubleWidthHeight(true,true).setTextBold(true).addText(msg).addLineFeed();
                  }else {
                     if(msg.startsWith("牌号")){
                        manager.setTextAlignLeft().setTextChartSet("GBK").addText(msg).setTextFontDoubleWidthHeight(true,true).setTextBold(true).addLineFeed();
                     }else {
                        manager.setTextAlignLeft().setTextChartSet("GBK").setTextFontDoubleWidthHeight(false,false).setTextBold(false).addText(msg).addLineFeed();
                     }
                  }
                  Bitmap bitmap = bitmapMap.get(i);
                  if (bitmap != null) {
                     manager.setAlignCenter().setBmpLimitWidth(40).addBmp(bitmap).addLineFeed();
                  }
               }

               if (bitmapMap.size() > 0) {
                  //传入的position位置大于list的话默认在最后面打印
                  for (Map.Entry<Integer, Bitmap> entry : bitmapMap.entrySet()) {
                     if (entry.getKey() > testList.size() - 1) {
                        Bitmap showBitmap = entry.getValue();
                        manager.setAlignCenter().setBmpLimitWidth(40).addBmp(showBitmap).addLineFeed();
                     }
                  }
               }
               //切纸
               posManager.sendEscMsgToPrinter(manager.useAllCutter().build());
               mCallBack.onPrintResult(true);
            } catch (Exception e) {
               e.printStackTrace();
               mCallBack.onPrintResult(false);
            }
         }
      });
   }

   @Override
   public void blueConnect(String address) {

   }

   @Override
   public void disBlueConnect() {

   }

   @Override
   public void openMoneyBox() {
      posManager.sendEscMsgToPrinter(new ESCCmdManager().openCashDrawer().build());
   }

   @Override
   public boolean isConnected() {
      return false;
   }
}
